package com.boe.csb.core.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boe.csb.core.common.pool.FtpClientPool;

/**
 * ftp 上传文件
 * date 2016年12月1日
 * @author xc
 */
public class FtpUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
	
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM/dd");
	
	public static String workDic = "./";
	
	private static int upSizeLimit = Integer.MAX_VALUE;//默认无限制
	
	private static FtpClientPool ftpPool = new FtpClientPool();
	
	static{
		workDic = PropertyUtils.getProperty("ftp.workDic");
		upSizeLimit = PropertyUtils.getIntProperty("ftp.UpSize.limit");
	}
	
	public static FTPClient getFtpClient(){
		try {
			return ftpPool.borrowObject();
		} catch(Exception e){
			logger.error("", e);
			return null;
		}
	}
	
	public static boolean upload(String fileName, File file){
		if(file.isDirectory()){//FIXME 只允许上传单个文件
			logger.error("limit for sigle file,but it is dictory. file:{}", file.getPath());
			return false;
		}
		
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			logger.error("", e);
			return false;
		}
		
		return upload(workDic, fileName, fis);
	}
	
	public static boolean upload(String dic, String fileName, File file){
		if(file.isDirectory()){//FIXME 只允许上传单个文件
			logger.error("limit for sigle file,but it is dictory. file:{}", file.getPath());
			return false;
		}
		
		FileInputStream fis;
		try {
			fis = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			logger.error("", e);
			return false;
		}
		
		return upload(dic, fileName, fis);
	}
	
	public static boolean upload(String fileName, InputStream inputStream) {
		return upload(workDic, fileName, inputStream);
	}
	
	/**
	 * FIXME 是否需要文件存在校验
	 * @param dicName
	 * @param fileName
	 * @param inputStream
	 * @return
	 */
	public static boolean upload(String dicName, String fileName, InputStream inputStream) {
		
		try {
			fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
		} catch (UnsupportedEncodingException e) {
			logger.error("", e);
		}
		
		try {
			if(upSizeLimit < inputStream.available()){
				logger.error("input size bigger then limit, input size:{}.", inputStream.available());
				return false;
			}
		} catch (IOException e) {
			logger.error("", e);
			return false;
		}
		
		FTPClient ftpClient = getFtpClient();
		if(ftpClient == null){
			return false;
		}
		
		boolean uploadSuccess = false;
		String currWork = null;
		try {
			currWork = ftpClient.printWorkingDirectory();
			if(!ftpClient.changeWorkingDirectory(dicName)){
				if(!createDir(dicName, ftpClient)){
					logger.info("ftp dic:{} not exists, create it failure!", dicName);
					return false;
				}
				
				if(!ftpClient.changeWorkingDirectory(dicName)){
					logger.info("ftp dic:{} not exists", dicName);
					return false;
				}
				
				logger.info("ftp dic:{} not exists, create it success!", dicName);
			}
			uploadSuccess = ftpClient.storeFile(fileName, inputStream);
		} catch (IOException e) {
			logger.info("upload error:", e);
		}finally{
			if(currWork != null){
				try{
					ftpClient.changeWorkingDirectory(currWork);
				}catch (Exception e1){
					invalidateObject(ftpClient);
				}
			}
			closeFtp(ftpClient);
		}
		
		return uploadSuccess;
	}
	
	public static boolean createDir(String dirName, FTPClient ftpClient){
		try{
			StringTokenizer dirs = new StringTokenizer(dirName, "/");
			String temp = null;
			boolean flag = false;
			String currWork = ftpClient.printWorkingDirectory();
			while (dirs.hasMoreElements()) {
				temp = dirs.nextElement().toString();
				if (!ftpClient.changeWorkingDirectory(temp)) {
					ftpClient.makeDirectory(temp);// 创建目录
					ftpClient.changeWorkingDirectory(temp);// 进入创建的目录
					flag = true;
				}
			}
			
			ftpClient.changeWorkingDirectory(currWork);
			return flag;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	
	public static byte[] download(String dicName, String fileName){

		FTPClient ftpClient = getFtpClient();
		if(ftpClient == null){
			return null;
		}
		
		byte result[] = new byte[0];
		InputStream ins = null;
		
		try{
			
			if(!ftpClient.changeWorkingDirectory(dicName)){
				logger.error("ftp dic:{} not exists!", dicName);
				return null;
			}
			
			FTPFile[] fileList = ftpClient.listFiles(fileName);
			if(fileList.length == 0){
				logger.error("can not find any file int dic:{} of filename:{}.", dicName, fileName);
				return null;
			}
			
			if(fileList.length > 1){
				logger.warn("get file size:{} from ftp big then 1. get the first of result.", fileName);
			}
			
			FTPFile ftpFile = fileList[0];
			if(ftpFile.isDirectory()){
				logger.error("get file:{} is a dictory.", fileName);
				return null;
			}
			
			ins = ftpClient.retrieveFileStream(fileName);
			BufferedInputStream inbf = new BufferedInputStream(ins);
			byte buffer[] = new byte[1024];
			int readCount;
			int length = 0;

			while( (readCount = inbf.read(buffer)) > 0) {
			      int preLength = length;
			      length += readCount;
			      byte newResult[] = new byte[length];
			      System.arraycopy(result, 0, newResult, 0, result.length);
			      System.arraycopy(buffer, 0, newResult, preLength, readCount); 
			      result = newResult;
			}
			
			return result;
		}catch(Exception e){
			logger.error("", e);
		}finally{
			if(ins != null){
				try {
					ins.close();
					ftpClient.completePendingCommand();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
			closeFtp(ftpClient);
		}
		
		return null;
	
	}
	
	/**
	 * FIXME 直接用read() != -1 得不到完整值
	 * @param fileName
	 * @return
	 */
	public static byte[] download(String fileName){
		return download(workDic, fileName);
	}
	
	public static void closeFtp(FTPClient ftp){
		try {
			ftpPool.returnObject(ftp);
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public static void invalidateObject(FTPClient ftp){
		try {
			ftpPool.invalidateObject(ftp);
		} catch (Exception e) {
			logger.error("", e);
		}
	}
	
	public static String getFtpFileName(String fileName){
		return fileName;
	}
	
	public static String getDatePath(){
		Date date = Calendar.getInstance().getTime();
		return "./" + sdf.format(date);
	}

}
